<template>
  <div class="mobile-server-monitor common-mobile-view">
    <server-card :is-online="appStore.isWebSocket"
                 :server-ip="appStore.serverIp"
                 :server-monitor="serverInfo.monitor"/>

    <server-progress :server-monitor="serverInfo.monitor"/>

    <div class="refresh-time">
      <el-text >{{ serverInfo.refreshTime }}</el-text>
    </div>
  </div>
</template>

<script lang="ts" setup>
import ServerCard from '@/components/Server/ServerCard.vue'
import ServerProgress from '@/components/Server/ServerProgress.vue'
import { useAppStore } from '@/store/app.ts'
import { onMounted, onUnmounted, reactive } from 'vue'
import { WebSocketUtil } from 'vue3-common/utils/webSocketUtil'
import { IServerMonitor } from '@/types/server.ts'
import { formatDate } from 'vue3-common/utils/dateUtil'

const appStore = useAppStore()

const webSocket = new WebSocketUtil(`ws://${appStore.serverIp}/ws/`)

const serverInfo = reactive({
  monitor: {
    cpuCores: 0,
    cpuModel: '',
    cpuUsage: 0,
    diskUsage: 0,
    memoryUsage: 0,
    networkSpeed: {
      rx: 0,
      tx: 0
    },
    systemInfo: '',
    systemLoad: {
      load1m: 0,
      load5m: 0,
      load15m: 0
    },
    topProcesses: [],
    totalDisk: 0,
    totalMemory: 0,
    uptime: 0
  } as IServerMonitor,
  refreshTime: formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')
})

onMounted(async () => {
  webSocket.connect()
})

onUnmounted(() => {
  webSocket.close()
})

webSocket.on('onOpen', () => {
  appStore.isWebSocket = true
  webSocket.send(webSocket.formatMessage('serverMonitor', {}))
  // console.log('连接成功')
})

webSocket.on('onMessage', (message: string) => {
  serverInfo.monitor = JSON.parse(message).payload
  serverInfo.refreshTime = formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')
  // console.log(serverInfo.monitor)
})

webSocket.on('onClose', (event: CloseEvent) => {
  appStore.isWebSocket = false
  // console.log('关闭连接')
})
</script>

<style lang="scss">
.mobile-server-monitor {
  display: flex;
  flex-direction: column;
  gap: 10px;

  .refresh-time {
    align-self: flex-end;
  }
}
</style>
